package com.idea.relax.log.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @className: DefaultThreadFactory
 * @description: 默认的线程池工厂
 * @author: salad
 * @date: 2023/1/8
 **/
@Slf4j
public class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup GROUP;
    private final AtomicInteger THREAD_NUMBER = new AtomicInteger(1);
    private final String namePrefix;

    public DefaultThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        GROUP = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = "RelaxLog-ThreadPool-" + POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(GROUP, r, namePrefix + THREAD_NUMBER.getAndIncrement(), 0);
        t.setUncaughtExceptionHandler((Thread thread, Throwable e) ->
                log.error("The thread pool task is exception,Thread name [" + thread.getName() + "]", e)
        );
        if (t.isDaemon()){
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY){
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
